package com.cgwx.service.impl;

import com.cgwx.auth.util.TreeUtil.TreeUtils;
import com.cgwx.config.BusinessException;
import com.cgwx.entity.File;
import com.cgwx.entity.Folder;
import com.cgwx.entity.PersonalRecycleBin;
import com.cgwx.entity.Room;
import com.cgwx.mapper.FileMapper;
import com.cgwx.mapper.FolderMapper;
import com.cgwx.mapper.PersonalRecycleBinMapper;
import com.cgwx.service.IPersonalRecycleBinService;
import com.cgwx.service.IRoomService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class PersonalRecycleBinServiceImpl implements IPersonalRecycleBinService {
    @Resource
    private PersonalRecycleBinMapper personalRecycleBinMapper;

    @Resource
    private FolderMapper folderMapper;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private IRoomService roomService;

    @Override
    public List<PersonalRecycleBin> getAllPersonalRecycleBin(String account, String roomId, String pattern, String column, String sort) {
        PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
        personalRecycleBin.setEntityName(pattern);
        personalRecycleBin.setEntityRoom(roomId);
        personalRecycleBin.setColumn(column);
        personalRecycleBin.setSort(sort);
        return personalRecycleBinMapper.getAllPersonalRecycleBin(personalRecycleBin);
    }

    @Override
    public List<PersonalRecycleBin> getCompanyRecycleBin(String account, String deptId, String companyRoomId, String entityName, String column, String sort) {
        return personalRecycleBinMapper.getCompanyRecycleBin(account, deptId, companyRoomId, entityName, column, sort);
    }

    @Override
    public List<PersonalRecycleBin> getDeptRecycleBin(String account, String deptId, String deptRoomId, String entityName, String column, String sort) {
        return personalRecycleBinMapper.getDeptRecycleBin(account, deptId, deptRoomId, entityName, column, sort);
    }

    @Override
    public List<PersonalRecycleBin> getFreeRecycleBin(String account, String deptId, String roomId, String entityName, String column, String sort) {
        return personalRecycleBinMapper.getFreeRecycleBin(account, deptId, roomId, entityName, column, sort);
    }

    @Override
    public List<PersonalRecycleBin> getPersonalRecycleBin(PersonalRecycleBin personalRecycleBin) {
        return personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
    }

    @Override
    public String deletePersonalRecycleBinById(String entityId) {
        boolean result = personalRecycleBinMapper.deletePersonalRecycleBinById(entityId);
        if(result) return "删除成功!";
        else return "删除失败!";
    }

    @Override
    @Transactional
    public String deleteRecycleBinEntirelyById(List<String> entityIds) {
        if(entityIds.isEmpty()) throw new BusinessException("请选择要彻底删除的文件（夹）");
        PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
        personalRecycleBin.setEntityId(entityIds.get(0));
        personalRecycleBin = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin).get(0);
        String roomId = personalRecycleBin.getEntityRoom();
        for(String entityId: entityIds){
            boolean result = personalRecycleBinMapper.deleteEntirely(entityId);
            if(!result){
                log.error("彻底删除失败!");
                throw new BusinessException("彻底删除失败!");
            }
            //空间大小
            float totalSize = 0;
            if(entityId.startsWith("file")){
                PersonalRecycleBin personalRecycleBinFile = new PersonalRecycleBin();
                personalRecycleBinFile.setEntityId(entityId);
                List<PersonalRecycleBin> personalRecycleBinFiles = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBinFile);
                if(personalRecycleBinFiles.isEmpty()){
                    log.error("回收站没有该文件!");
                    throw new BusinessException("回收站没有该文件!");
                }
                totalSize = personalRecycleBinFiles.get(0).getFileSize();
            }
            else if(entityId.startsWith("folder")){
                File file = new File();
                file.setParentId(entityId);
                List<File> files = fileMapper.getFile(file);
                for(File file1: files) totalSize += file1.getFileSize();

                List<Folder> folders = folderMapper.getAllFolderByRoomId(roomId);
                folders = TreeUtils.build(folders, entityId);
                for(Folder folder: folders){
                    List<Folder> folders1 = TreeUtils.root2List(folder);
                    for(Folder folder1 :folders1){
                        file = new File();
                        file.setParentId(folder1.getEntityId());
                        files = fileMapper.getFile(file);
                        for(File file1: files) totalSize += file1.getFileSize();
                    }
                }
            }
            else {
                log.error("entityId有误!");
                throw new BusinessException("entityId有误!");
            }
            Room room = new Room();
            room.setId(roomId);
            room.setUsedSpace(-totalSize);
            if(roomService.updateRoomById(room).equals("更新失败!")){
                log.error("彻底删除更新失败!");
                throw new BusinessException("彻底删除失败!");
            }
        }
        return "彻底删除成功!";
    }

    @Override
    @Transactional
    public String insertRecycleBin(String entityId, String deleteAccount) {
        if (entityId.startsWith("folder")) {
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            List<Folder> list = folderMapper.getFolder(folder);
            if (list.isEmpty()) {
                log.error("没有该entityId!(1)");
                throw new BusinessException("没有该entityId!");
            }
            else if (list.size() > 1){
                log.error("存在多个该entityId!(1)");
                throw new BusinessException("存在多个该entityId!");
            }
            else {
                folder = list.get(0);
                PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
                personalRecycleBin.setDeleteTime(time);
                personalRecycleBin.setEntityId(folder.getEntityId());
                personalRecycleBin.setEntityName(folder.getEntityName());
                personalRecycleBin.setEntityRoom(folder.getEntityRoom());
                personalRecycleBin.setOwnerAccount(folder.getOwnerAccount());
                personalRecycleBin.setOwnerName(folder.getOwnerName());
                personalRecycleBin.setParentId(folder.getParentId());
                personalRecycleBin.setFileOrFolder("folder");
                personalRecycleBin.setType(folder.getType());
                personalRecycleBin.setTag(folder.getTag());
                personalRecycleBin.setCreateTime(folder.getCreateTime());
                personalRecycleBin.setUpdateTime(folder.getUpdateTime());
                personalRecycleBin.setDeleteEntirely("false");
                personalRecycleBin.setDeleteAccount(deleteAccount);
                String parentId = folder.getParentId();
                StringBuilder parentPath = new StringBuilder();
                StringBuilder parentPathname = new StringBuilder();
                Room room = new Room();
                room.setId(folder.getEntityRoom());
                String roomName = roomService.getRoom(room).get(0).getRoomName();

                while (parentId != null && !parentId.equals("root")) {
                    folder = new Folder();
                    folder.setEntityId(parentId);
                    folder = folderMapper.getFolder(folder).get(0);
                    parentPath.insert(0, folder.getEntityId() + ",");
                    parentPathname.insert(0, folder.getEntityName() + "/");
                    parentId = folder.getParentId();
                }
                parentPathname.insert(0, roomName + "的空间/");
                String path = parentPath.toString();
                if (!path.isEmpty()) {
                    personalRecycleBin.setParentPath(parentPath.substring(0, parentPath.length() - 1));
                    personalRecycleBin.setParentPathname(parentPathname.substring(0, parentPathname.length() - 1));
                }
                boolean result = personalRecycleBinMapper.insertPersonalRecycleBin(personalRecycleBin);
                if (!result){
                    log.error("回收站新增文件(夹)失败!(1)");
                    throw new BusinessException("回收站新增文件(夹)失败!");
                }
            }
        } else if (entityId.startsWith("file")) {
            File file = new File();
            file.setEntityId(entityId);
            List<File> list = fileMapper.getFile(file);
            if (list.isEmpty()){
                log.error("没有该entityId!(2)");
                throw new BusinessException("没有该entityId!");
            }
            else if (list.size() > 1){
                log.error("存在多个该entityId!(2)");
                throw new BusinessException("存在多个该entityId!");
            }
            else {
                file = list.get(0);
                PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                Timestamp time = Timestamp.valueOf(LocalDateTime.now());
                personalRecycleBin.setDeleteTime(time);
                personalRecycleBin.setEntityId(file.getEntityId());
                personalRecycleBin.setEntityName(file.getEntityName());
                personalRecycleBin.setEntityRoom(file.getEntityRoom());
                personalRecycleBin.setOwnerAccount(file.getOwnerAccount());
                personalRecycleBin.setOwnerName(file.getOwnerName());
                personalRecycleBin.setParentId(file.getParentId());
                personalRecycleBin.setFileOrFolder("file");
                personalRecycleBin.setFileId(file.getFileId());
                personalRecycleBin.setFileUrl(file.getFileUrl());
                personalRecycleBin.setVersionId(file.getVersionId());
                personalRecycleBin.setType(file.getType());
                personalRecycleBin.setTag(file.getTag());
                personalRecycleBin.setCreateTime(file.getCreateTime());
                personalRecycleBin.setUpdateTime(file.getUpdateTime());
                personalRecycleBin.setDeleteEntirely("false");
                personalRecycleBin.setFileSize(file.getFileSize());
                personalRecycleBin.setDeleteAccount(deleteAccount);
                String parentId = file.getParentId();
                StringBuilder parentPath = new StringBuilder();
                StringBuilder parentPathname = new StringBuilder();
                Folder folder;
                Room room = new Room();
                room.setId(file.getEntityRoom());
                String roomName = roomService.getRoom(room).get(0).getRoomName();
                while (parentId != null && !parentId.equals("root")) {
                    folder = new Folder();
                    folder.setEntityId(parentId);
                    folder = folderMapper.getFolder(folder).get(0);
                    parentPath.insert(0, folder.getEntityId() + ",");
                    parentPathname.insert(0, folder.getEntityName() + "/");
                    parentId = folder.getParentId();
                }
                parentPathname.insert(0, roomName + "的空间/");
                String path = parentPath.toString();
                if (!path.isEmpty()) {
                    personalRecycleBin.setParentPath(parentPath.substring(0, parentPath.length() - 1));
                    personalRecycleBin.setParentPathname(parentPathname.substring(0, parentPathname.length() - 1));
                }
                boolean result = personalRecycleBinMapper.insertPersonalRecycleBin(personalRecycleBin);
                if (!result){
                    log.error("回收站新增文件(夹)失败!(2)");
                    throw new BusinessException("回收站新增文件(夹)失败!");
                }
            }
        }
        else{
            log.error("没有该entityId!");
            throw new BusinessException("没有该entityId!");
        }
        return "回收站新增文件(夹)成功!";
    }
}